package org.kunteng.yunac.lttask.controller.view;

import org.kunteng.yunac.lttask.AbstractTask;
import org.kunteng.yunac.lttask.LTTaskManager;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by hedingwei on 6/5/15.
 */
@Controller
@RequestMapping("${adminPath}/f/lttask")
public class View {
    private ModelAndView view = new ModelAndView("f/lttask/view");
    @Autowired
    private LTTaskManager longTimeTaskRunner;

    @RequestMapping(value = "task.view.do")
    public ModelAndView action(HttpServletRequest request,@RequestParam("logId")int logId) {

            AbstractTask abstractTask = longTimeTaskRunner.getHistoryTaskLog(logId);
            if(abstractTask==null){
                view.addObject("hasHistoryTask", false);
            }else{
                view.addObject("hasHistoryTask", true);
                view.addObject("task_model", abstractTask.getModel());
            }
            view.addObject("isRunning", false);
            return view;
    }

    @RequestMapping(value = "taskview.json.do")
    @ResponseBody
    public JSONObject action(HttpServletRequest request,@RequestParam("lttid")String lttid) {

        AbstractTask abstractTask = longTimeTaskRunner.getRunningTasks().get(lttid);

        if(abstractTask==null){

            AbstractTask ltask = longTimeTaskRunner.getLastTask(lttid);

            if(ltask==null){
                JSONObject result = new JSONObject();
                result.put("hasTask", false);
                return result;
            }else{
                JSONObject result = JSONObject.fromObject(ltask.getModel());
                result.put("hasTask", true);
                return result;
            }
        }else{
            JSONObject result = JSONObject.fromObject(abstractTask.getModel());
            result.put("hasTask", true);
            return result;
        }

    }
}
